﻿using BaseUtils.Helper;
using MyMes.Mes;
using Newtonsoft.Json;
using NWMES.Mes;
using NWMES.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace NWMES.HttpClientUtil
{
    public class HttpRequest : MESBaseService
    {
        public async Task<string> Get()
        {
            using (HttpClient client = new HttpClient())
            {
                // 设置请求头
                client.DefaultRequestHeaders.Add("User-Agent", "MyApp/1.0");

                // 构建请求参数
                string baseUrl = "https://jsonplaceholder.typicode.com/posts";
                string queryParams = "?userId=1";
                string requestUrl = baseUrl + queryParams;

                try
                {
                    // 发送 GET 请求
                    HttpResponseMessage response = await client.GetAsync(requestUrl);
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine($"请求出错: {e.Message}");
                }
            }
            return "";
        }

        //public async Task<T> Post2<T>(RequestParam Param)
        //{
        //    string responseBody = null;
        //    using (HttpClient client = new HttpClient())
        //    {
        //        // 设置请求头
        //        client.DefaultRequestHeaders.Add("User-Agent", "MyApp/1.0");
        //        client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("username:password")));

        //        // 构建请求体
        //        var data = new { title = "foo", body = "bar", userId = 1 };
        //        string json = JsonConvert.SerializeObject(data);
        //        HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");

        //        try
        //        {
        //            // 发送 POST 请求
        //            HttpResponseMessage response = await client.PostAsync("https://jsonplaceholder.typicode.com/posts", content);
        //            response.EnsureSuccessStatusCode();

        //            // 读取响应内容
        //             responseBody = await response.Content.ReadAsStringAsync();
        //            Console.WriteLine(responseBody);
        //        }
        //        catch (HttpRequestException e)
        //        {
        //            Console.WriteLine($"请求出错: {e.Message}");
        //        }
        //    }
        //    return ConvertHelper.ToObject<T>(responseBody);
        //}

        /// <summary>
        /// MES收数
        /// 常用来带数据出站
        /// </summary>
        /// <param name="sfc"></param>
        /// <param name="MesData"></param>
        /// <param name="ApiSection"></param>
        /// <returns></returns>
        public static async Task<MesResult> Post(MESBaseService Param)
        {

            var requestParams = Param.ToJson().ToObject<Dictionary<string, object>>();
            //var requestParams = new Dictionary<string, object>
            //{
            //    { "site", Params.Site },
            //    { "user", Params.User },
            //    { "operation", Params.Operation },
            //    { "operationRevision", Params.OperationRevision },
            //    { "activityId", Params.ActivityId },
            //    { "resource", Params.Resource },
            //    { "dcGroup", Params.DcGroup },
            //    { "dcGroupRevision", Params.DcGroupRevision },
            //    { "modeProcessSfc", ConvertHelper.ToEnum<dataCollectForSfcModeProcessSfc>(Params.ModeProcessSFC).ToString() },
            //    { "sfc", sfc }
            //};

            //if (MesData?.Count > 0)
            //{
            //    requestParams["parametricDataArray"] = MesData.Select(a =>
            //    {
            //        return new Dictionary<string, object>
            //        {
            //            { "name", a.Name },
            //            { "value", a.Value },
            //            { "dataType", a.DataType }
            //        };
            //    }).ToList();
            //}

            var result = MesResult.InitMesResult(JsonConvert.SerializeObject(requestParams));

            try
            {  // 创建自定义的 Windows 域凭证
                NetworkCredential networkCredential = new NetworkCredential(Param.UserName, Param.Password);
                // 创建 HttpClientHandler 实例
                HttpClientHandler handler = new HttpClientHandler
                {
                    // 使用自定义的 Windows 域凭证
                    Credentials = networkCredential
                };
                using (var httpClient = new HttpClient(handler))
                {
                    httpClient.Timeout = TimeSpan.FromMilliseconds(Param.Timeout);
                    var byteArray = Encoding.ASCII.GetBytes($"{Param.UserName}:{Param.Password}");
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

                    var soapRequest = BuildSoapRequest(Param.ActionName, Param.RequestElementName, requestParams);
                    //var soapRequest = BuildSoapRequest("dataCollectForModuleTest", "DcForModuleTestRequest", requestParams);
                    StringContent content = new StringContent(soapRequest.ToString(), Encoding.UTF8, "text/xml");
                    var response = await httpClient.PostAsync(Param.Url, content);

                    result.EndTime = DateTime.Now;

                    if (response.IsSuccessStatusCode)
                    {
                        var responseBody = await response.Content.ReadAsStringAsync();
                        var responseXml = XDocument.Parse(responseBody);
                        var retElement = responseXml.Descendants("{http://tempuri.org/}return").FirstOrDefault();
                        if (retElement != null)
                        {
                            var messageElement = retElement.Element("{http://tempuri.org/}message");
                            var codeElement = retElement.Element("{http://tempuri.org/}code");
                            result.Message = messageElement?.Value;
                            result.Code = int.Parse(codeElement?.Value ?? "-1");
                            result.Success = result.Code == 0;
                            result.ResponeJson = responseBody;
                        }
                    }
                    else
                    {
                        result.Code = (int)response.StatusCode;
                        result.Message = await response.Content.ReadAsStringAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                result.Code = -99;
                result.Message = ex.Message;
            }

            SaveMesLog(Param.InterfaceName, result);
            return result;
        }

        public static async Task Main3()
        {
            try
            {
                // 目标 URL
                string url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx";

                // 定义要查询的手机号码和用户 ID（免费用户为空字符串）
                string mobileCode = "18059223611";
                string userID = "";

                Dictionary<string, object> requestParams = new Dictionary<string, object>();
                requestParams.Add("mobileCode", "18059223611");
                requestParams.Add("userID", "");
                var soapRequest2 = BuildSoapRequest("getMobileCodeInfo", "DcForModuleTestRequest", requestParams);

                // 构建 SOAP 请求体
                string soapRequest = @"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
  <soap:Body>
    <getMobileCodeInfo xmlns=""http://WebXml.com.cn/"">
      <mobileCode>" + mobileCode + @"</mobileCode>
      <userID>" + userID + @"</userID>
    </getMobileCodeInfo>
  </soap:Body>
</soap:Envelope>";


                // 创建 HttpClient 实例
                using (HttpClient client = new HttpClient())
                {
                    // 设置请求头
                    //client.DefaultRequestHeaders.Add("SOAPAction", "http://WebXml.com.cn/getMobileCodeInfo");
                    //client.DefaultRequestHeaders.Add("Content-Type", "text/xml; charset=utf-8");
                    StringContent content = new StringContent(soapRequest2.ToString(), Encoding.UTF8, "text/xml");

                    // 创建请求内容
                    //var content = new StringContent(GenerateSoapRequest("getMobileCodeInfo", requestParams).ToString(), Encoding.UTF8, "text/xml");

                    // 发送 POST 请求
                    HttpResponseMessage response = await client.PostAsync(url, content);

                    // 检查响应状态
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容
                    string responseBody = await response.Content.ReadAsStringAsync();

                    // 输出响应内容
                    Console.WriteLine("响应内容: " + responseBody);
                }
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine("调用接口时发生错误: " + ex.Message);
            }
        }

        public static string GenerateSoapRequest(string actionName,Dictionary<string, object> parameters)
        {
            // 定义 SOAP 命名空间
            XNamespace soapNs = "http://schemas.xmlsoap.org/soap/envelope/";
            XNamespace xsiNs = "http://www.w3.org/2001/XMLSchema-instance";
            XNamespace xsdNs = "http://www.w3.org/2001/XMLSchema";
            string targetNamespace = "http://WebXml.com.cn/";
            // 创建 SOAP 信封
            var soapEnvelope = new XElement(soapNs + "Envelope",
                new XAttribute(XNamespace.Xmlns + "soap", soapNs),
                new XAttribute(XNamespace.Xmlns + "xsi", xsiNs),
                new XAttribute(XNamespace.Xmlns + "xsd", xsdNs),
                new XElement(soapNs + "Body",
                    new XElement(actionName,
                      new XAttribute(XNamespace.Xmlns + "", targetNamespace),
                        parameters.Select(kvp => new XElement(kvp.Key, kvp.Value))
                    )
                )
            );

            // 创建 XDocument 并添加 SOAP 信封
            var doc = new XDocument(soapEnvelope);

            // 返回 XML 字符串
            return doc.ToString();
        }

        public static void Main2()
        {
            try
            {
                // 创建服务客户端实例
                MobilecnCodeService.MobileCodeWS client = new MobilecnCodeService.MobileCodeWS();

                // 定义要查询的手机号码和用户 ID（免费用户为空字符串）
                string mobileCode = "13800138000";
                string userID = "";

                // 调用接口方法
                string result = client.getMobileCodeInfo(mobileCode, userID);

                // 输出结果
                Console.WriteLine("手机号码归属地信息: " + result);
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine("调用接口时发生错误: " + ex.Message);
            }
        }
        //public static async Task<MesResult> RequestMes(
        //  string sfc, List<MachineIntegrationParamData> MesData,
        //  string ApiSection)
        //{
        //    if (!string.IsNullOrEmpty(ApiSection))
        //    {
        //        Params = config[ApiSection].ToObject<MachineIntegration>();
        //        networkCredential = new NetworkCredential(Params.UserName, Params.Password);
        //    }
        //    else
        //    {
        //        ApiSection = DefaultApiSection;
        //    }
        //    string ErrorMessage = Params.ParameterVerification();
        //    if (!string.IsNullOrEmpty(ErrorMessage))
        //    {
        //        return new MesResult(-1, ErrorMessage);
        //    }

        //    var request = new dcForModuleTestRequest();
        //    SetRequestParams(request);

        //    request.sfc = sfc;

        //    if (MesData?.Count > 0)
        //    {
        //        request.parametricDataArray = MesData.Select(a =>
        //        {
        //            machineIntegrationParametricData param = new machineIntegrationParametricData() { name = a.Name, value = a.Value, dataType = a.DataType };
        //            return param;
        //        }).ToArray();
        //    }

        //    var result = MesResult.InitMesResult(JsonConvert.SerializeObject(request));

        //    try
        //    {
        //        using (var httpClient = new HttpClient())
        //        {
        //            httpClient.Timeout = TimeSpan.FromMilliseconds(Params.Timeout);
        //            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
        //                "Basic",
        //                Convert.ToBase64String(Encoding.ASCII.GetBytes($"{Params.UserName}:{Params.Password}")));

        //            var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
        //            var response = await httpClient.PostAsync(Params.Url, content);
        //            result.EndTime = DateTime.Now;

        //            if (response.IsSuccessStatusCode)
        //            {
        //                var responseBody = await response.Content.ReadAsStringAsync();
        //                var responseObject = JsonConvert.DeserializeObject<dataCollectForModuleTestResponse>(responseBody);
        //                var ret = responseObject.@return;
        //                result.Message = ret?.message;
        //                result.Code = ret.code;
        //                result.Success = result.Code == 0;
        //                result.Respone = responseBody;
        //            }
        //            else
        //            {
        //                result.Code = (int)response.StatusCode;
        //                result.Message = await response.Content.ReadAsStringAsync();
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        result.Code = -1;
        //        result.Message = ex.Message;
        //    }

        //    SaveMesLog(ApiSection, result);
        //    return result;
        //}

        public async Task<string> Put()
        {
            using (HttpClient client = new HttpClient())
            {
                // 设置请求头
                client.DefaultRequestHeaders.Add("User-Agent", "MyApp/1.0");

                // 构建请求体
                var data = new { id = 1, title = "updated title", body = "updated body", userId = 1 };
                string json = JsonConvert.SerializeObject(data);
                HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");

                try
                {
                    // 发送 PUT 请求
                    HttpResponseMessage response = await client.PutAsync("https://jsonplaceholder.typicode.com/posts/1", content);
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine($"请求出错: {e.Message}");
                }
            }
            return "";
        }

        public async Task<string> Delete()
        {
            using (HttpClient client = new HttpClient())
            {
                // 设置请求头
                client.DefaultRequestHeaders.Add("User-Agent", "MyApp/1.0");

                try
                {
                    // 发送 DELETE 请求
                    HttpResponseMessage response = await client.DeleteAsync("https://jsonplaceholder.typicode.com/posts/1");
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine($"请求出错: {e.Message}");
                }
            }
            return "";
        }
    }
}
